import { GameObject } from "./GameObject";
import { StarPoint } from "./StarPoint";
import { GamePiece } from "./GamePiece";
export class GameMap extends GameObject{
    constructor(ctx,parent,store){
        super(); //super的时候加入队列
        this.ctx = ctx;
        this.parent = parent;
        this.store = store;
        this.L = 0;
        //最简单的方式是多画两行格子，去掉最外圈的格子
        this.cols = store.state.pk.cols;
        this.rows = store.state.pk.rows;
        this.starPoints = [];
        this.board = Array(16).fill().map(() => Array(16).fill(0));
    }

    create_stars(){
        this.starPoints.push(new StarPoint(4,4,this));
        this.starPoints.push(new StarPoint(4,12,this));
        this.starPoints.push(new StarPoint(12,4,this));
        this.starPoints.push(new StarPoint(12,12,this));
        this.starPoints.push(new StarPoint(8,8,this));
    }
    start(){
        this.create_stars();
        this.add_listening_events();
    }

    update_size(){
        this.L = parseInt(Math.min(this.parent.clientWidth / this.cols,this.parent.clientHeight / this.rows));
        this.ctx.canvas.width = this.L * this.cols;
        this.ctx.canvas.height = this.L * this.rows;
    }

    add_listening_events(){

        if(this.store.state.record.is_Record){ //如果是对局回放，就不用聚焦啦
            let k =0;
            const steps = JSON.parse(this.store.state.record.steps);
            //const loser = this.store.state.record.record_loser;
            
            const interval_id = setInterval(() => { //每350毫秒执行一次
                if(k >= steps.length){
                    //结束循环
                    clearInterval(interval_id);//通过id来识别
                }
                else{
                    //接下来回合制 参考后端传来event=='move'
                    const game = this.store.state.pk.gameObject;
                    if(k%2==0){
                        new GamePiece({id:this.store.state.user.id,c:steps[k].col,r:steps[k].row,color:"#000000"},game);
                        //store.commit("updatePlayer","2");
                    }else{
                        new GamePiece({id:this.store.state.user.id,c:steps[k].col,r:steps[k].row,color:"#FFFFFF"},game);
                        //store.commit("updatePlayer","1");
                    }
                }
                k++;
            }, 350); //这里时间如果太少最后一个格子有可能画不满，如果时间太长可能会一卡一卡的
        }
        else{
            this.ctx.canvas.focus();  //获取键盘数据需要聚焦
            let player = parseInt(this.store.state.user.id) === this.store.state.pk.a_id ?  1 : 2; //必须要放到监听器外面
            this.ctx.canvas.addEventListener("click",e=>{

                // 1. 获取当前点击的位置（相对 canvas 左上角）
                const rect = this.ctx.canvas.getBoundingClientRect();
                const mouseX = e.clientX - rect.left;
                const mouseY = e.clientY - rect.top;
                
                // 2. 计算最近的交叉点（网格坐标）
                // 注意：每个格子边长为 L，交叉点位于格子顶点
                const col = Math.round(mouseX / this.L);
                const row = Math.round(mouseY / this.L);

                //当前游戏回合的游戏玩家 和后端发来的相匹配才可以发送到后端
                if(col && row && parseInt(this.store.state.pk.player) == player){
                    this.store.state.pk.socket.send(JSON.stringify({
                        event:"move",
                        col:parseInt(col),
                        row:parseInt(row),
                        currentPlayer:player
                    }));
                }
            })
        }
        
    }

    update(){
        this.update_size();
        this.render();
    }

    render(){
        const background_color = "#DEB887";

        for(let c=0;c<this.cols ;c++){
            for(let r=0;r<this.rows;r++){
                this.ctx.fillStyle = background_color;
                this.ctx.fillRect(c*this.L , r*this.L ,this.L,this.L);

                if(r==0|| c==0 ||r==this.rows-1 ||c==this.cols-1) continue;
                //先把游戏跑通再去看直接划线的做法
                //this.ctx.strokeRect(c*this.L , r*this.L, this.L, this.L);
            }
        }

        //canvas (xc,yr)
        //画横线 (1,r) (this.cols-1,r)
        for(let r=1;r<this.rows;r++){
            this.ctx.beginPath();
            this.ctx.moveTo(1*this.L,r*this.L);
            this.ctx.lineTo((this.cols-1)*this.L, r*this.L);
            // ctx.closePath(); 如果想线条粗可以直接画一个封闭的相当于画两遍
            this.ctx.stroke();
        }
        //画竖线 (c,1) (c,this.this.rows-1)
        for(let c=1;c<this.cols;c++){
            this.ctx.beginPath();
            this.ctx.moveTo(c*this.L, 1*this.L);
            this.ctx.lineTo(c*this.L, (this.rows-1)*this.L);
            this.ctx.stroke();
        }
    }
}